源代码
class SequentialList {
constructor() {
this.data = [];
this.length = 0;
}
// 初始化顺序表
init(arr) {
this.data = [...arr];
this.length = arr.length;
}
// 获取元素
getElement(index) {
if (index < 0 || index >= this.length) {
throw new Error('Index out of bounds');
}
return this.data[index];
}
// 获取长度
getLength() {
return this.length;
}
}
// 查找最后一个最小元素的序号
function findLastMinIndex(L) {
if (L.getLength() === 0) return -1; // 空表返回-1
let minValue = L.getElement(0);
let lastIndex = 0;
for (let i = 1; i < L.getLength(); i++) {
const current = L.getElement(i);
// 当遇到小于等于当前最小值的元素时更新
if (current <= minValue) {
minValue = current;
lastIndex = i;
}
}
return lastIndex;
}
// 测试用例
const seqList = new SequentialList();
seqList.init([1, 5, 1, 1, 3, 2, 4]); // 示例数据
console.log('最后一个最小值的序号:', findLastMinIndex(seqList)); // 输出: 3
seqList.init([5, 3, 3, 2, 4, 2, 1]); // 多个最小值
console.log('最后一个最小值的序号:', findLastMinIndex(seqList)); // 输出: 6
seqList.init([7]); // 只有一个元素
console.log('最后一个最小值的序号:', findLastMinIndex(seqList)); // 输出: 0
seqList.init([3, 3, 3]); // 所有元素相同
console.log('最后一个最小值的序号:', findLastMinIndex(seqList)); // 输出: 2
运行结果
> 等待执行...
代码解释
顺序表类定义
定义了顺序表类SequentialList,包含数据存储数组和长度属性,并提供初始化、获取元素和获取长度的方法。
查找算法
实现了查找最后一个最小元素序号的算法,通过遍历顺序表,不断更新最小值和其位置。
测试用例
提供了多组测试数据,包括普通情况、多个最小值、单元素和所有元素相同的情况,验证算法正确性。